package com.ruicar.afs.cloud.risk.tortoise.util;

import cn.hutool.core.util.ImageUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;


import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * @Description 面签照片处理，需上送的面签照片需要缩放处理
 * @Author Peng Jinbo
 * @Date 2020/08/05 9:54
 */
@UtilityClass
@Slf4j
public class SignPictureUtil {

    /**
     * Max size
     * 图片大小上限 23KB
     */
    final int MAX_SIZE = 23552;

    /**
     * Base scale
     * 每次缩放倍率 0.5
     */
    final int BASE_SCALE = 2;

    /**
     * Min width
     * 图片最小宽
     */
    final int MIN_WIDTH = 50;

    /**
     * Min height
     * 图片最小高
     */
    final int MIN_HEIGHT = 50;

    /**
     * Author Peng Jinbo
     * Shrink string
     *
     * @param imageBytesStr image bytes str
     * @return the string
     */
    public String shrink(String imageBytesStr) {
        try {
            byte[] imageBytes = Base64.getDecoder().decode(imageBytesStr);
            if(imageBytes.length < MAX_SIZE){
                return imageBytesStr;
            }else {
                BufferedImage bufferedImage = ImageUtil.toImage(imageBytes);
                return Base64.getEncoder().encodeToString(loopHalfShrink(bufferedImage));
            }
        } catch (Exception e) {
            log.error("",e);
            throw new AfsBaseException();
        }
    }

    /**
     * Author Peng Jinbo
     * Loop half shrink byte [ ]
     * 循环缩放，每次按 1/2 比例缩放，直到小于23K
     *
     * @param bufferedImage buffered image
     * @return the byte [ ]
     */
    private byte[] loopHalfShrink(BufferedImage bufferedImage){
        int finalWidth = bufferedImage.getWidth() / BASE_SCALE;
        int finalHeight = bufferedImage.getHeight() / BASE_SCALE;
        BufferedImage bi = (BufferedImage) ImageUtil.scale(bufferedImage, finalWidth, finalHeight);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageUtil.writeJpg(bi, os);
        if (os.toByteArray().length > MAX_SIZE) {
            return loopHalfShrink(bi);
        } else {
            return os.toByteArray();
        }
    }

}
